package cn.yhp.mybatis.session.defaults;

import cn.yhp.mybatis.executor.Executor;
import cn.yhp.mybatis.mapping.Environment;
import cn.yhp.mybatis.session.Configuration;
import cn.yhp.mybatis.session.SqlSession;
import cn.yhp.mybatis.session.SqlSessionFactory;
import cn.yhp.mybatis.session.TransactionIsolationLevel;
import cn.yhp.mybatis.transaction.Transaction;
import cn.yhp.mybatis.transaction.TransactionFactory;

import java.sql.SQLException;

/**
 * @author yhp
 * @description 默认SqlSessionFactory实现
 * @date 2023/11/8
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

//    private final MapperRegistry mapperRegistry;

    private final Configuration configuration;


    public DefaultSqlSessionFactory(Configuration configuration){
        this.configuration=configuration;
    }

    @Override
    public SqlSession openSession() {
        Transaction tx=null;
        try {
            // 创建事务【通过事务管理器】
            Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();
            tx=transactionFactory.newTransaction(configuration.getEnvironment().getDataSource(),
                    TransactionIsolationLevel.READ_COMMITTED,false);
            // 创建执行器
            Executor executor = configuration.newExecutor(tx);
            return new DefaultSqlSession(configuration,executor);
        }catch (Exception e) {
            try {
                assert tx != null;
                tx.close();
            } catch (SQLException ignore) {
            }
            throw new RuntimeException("Error opening session.  Cause: " + e);
        }

    }

}
